package bb.lanxing.lib.devices.sprint.ymodem;

import android.text.TextUtils;
import bb.lanxing.lib.devices.core.exception.InvalidDataException;
import bb.lanxing.lib.devices.core.exception.TimeoutException;
import bb.lanxing.lib.devices.sprint.utils.SprintSyncLogFileUtils;
import bb.lanxing.lib.devices.utils.ByteUtils;
import bb.lanxing.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;

public class YModenOutputStream extends OutputStream {
    private static final String STUFFIX_TMP = ".tmp";
    private long bytesReceived;
    private long fileLength;
    private String fileName;
    private ByteBuffer mBuffer;
    private final Object mLock;
    private int mPackageSize;
    private File mRootDir;

    public YModenOutputStream(File file) {
        this.mPackageSize = 133;
        this.mLock = new Object();
        this.mRootDir = file;
    }

    public YModenOutputStream(String str) {
        this(new File(str));
    }

    @Override
    public void write(int i) throws IOException {
        synchronized (this.mLock) {
            ByteBuffer byteBuffer = this.mBuffer;
            if (byteBuffer == null || byteBuffer.position() == 0) {
                int i2 = 133;
                if (((byte) i) == 2) {
                    i2 = YModems.PACKAGE_SIZE_BIG;
                }
                if (this.mPackageSize != i2 || this.mBuffer == null) {
                    this.mPackageSize = i2;
                    this.mBuffer = ByteBuffer.allocate(i2);
                }
            }
            try {
                this.mBuffer.put((byte) i);
            } catch (BufferOverflowException e) {
                e.printStackTrace();
            }
            if (hasPacket()) {
                this.mLock.notifyAll();
            }
        }
    }

    public YModem readPacket() throws InvalidDataException, TimeoutException {
        synchronized (this.mLock) {
            if (!hasPacket()) {
                try {
                    this.mLock.wait(5000L);
                } catch (InterruptedException e) {
                    SprintSyncLogFileUtils.saveSyncELog("InterruptedException : YModenOutputStream Line86");
                    throw new InvalidDataException(e);
                }
            }
            if (!hasPacket()) {
                SprintSyncLogFileUtils.saveSyncELog("check packet...already waiting 5000ms for full buffer, :YModenOutputStream Line91");
                throw new TimeoutException("");
            }
        }
        YModem pack = pack();
        if (YModems.checkCRC(pack)) {
            long j = 0;
            if (!TextUtils.isEmpty(this.fileName)) {
                if (this.bytesReceived + pack.data.length > this.fileLength) {
                    pack.data = YModems.truncate(pack.data, (int) (this.fileLength - this.bytesReceived));
                }
                j = pack.data.length;
            }
            this.bytesReceived = Math.min(this.bytesReceived + j, this.fileLength);
            onReceived(pack);
            reset();
            return pack;
        }
        reset();
        SprintSyncLogFileUtils.saveSyncELog("**************CRC ERROR: " + ((int) pack.getCrc()) + "*************");
        throw new InvalidDataException("CRC ERROR: " + ((int) pack.getCrc()));
    }

    public boolean transferTo(String str) {
        File file = this.mRootDir;
        File file2 = new File(file, this.fileName + STUFFIX_TMP);
        Log.d("wangsm_bt"," YmodenOutputStream , transferTo this.fileName: " + this.fileName);
        Log.d("wangsm_bt"," YmodenOutputStream , transferTo str: " + str);
        if (!file2.exists()) {
            return false;
        }
        return file2.renameTo(new File(str));
    }

    private void onReceived(YModem yModem) {
        if (TextUtils.isEmpty(this.fileName)) {
            String[] split = ByteUtils.bytesToString(yModem.data, "iso-8859-1").trim().split(" ");
            this.fileName = split[0];
            this.fileLength = Long.parseLong(split[1]);
            File file = this.mRootDir;
            File file2 = new File(file, this.fileName + STUFFIX_TMP);
            if (!file2.exists()) {
                return;
            }
            file2.delete();
            return;
        }
        try {
            File file3 = this.mRootDir;
            File targetFile = new File(file3, this.fileName + STUFFIX_TMP);
            FileOutputStream fileOutputStream = new FileOutputStream(targetFile, true);
            Log.d("wangsm_bt" , " begin write file to json data,the file is " + targetFile.getAbsolutePath());
            fileOutputStream.write(yModem.data);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public long getTotalBytes() {
        return this.fileLength;
    }

    public String getFileName() {
        return this.fileName;
    }

    public long getBytesReceived() {
        return this.bytesReceived;
    }

    public boolean hasPacket() {
        boolean z;
        synchronized (this.mLock) {
            ByteBuffer byteBuffer = this.mBuffer;
            z = byteBuffer != null && !byteBuffer.hasRemaining();
        }
        return z;
    }

    public void reset() {
        synchronized (this.mLock) {
            ByteBuffer byteBuffer = this.mBuffer;
            if (byteBuffer != null) {
                byteBuffer.clear();
            }
            this.mLock.notifyAll();
        }
    }

    private YModem pack() {
        byte[] bArr = new byte[this.mPackageSize];
        this.mBuffer.flip();
        this.mBuffer.get(bArr);
        return YModems.createYModem(bArr);
    }
}
